﻿using DevComponents.DotNetBar;
using DevComponents.DotNetBar.SuperGrid;
using Kimd.Common;
using Kimd.Logic;
using Kimd.Machine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WorkStation.Common;

namespace WorkStation.UI
{
    public partial class FormAlarm : Office2007Form
    {
        private FormMain _mainForm;
        public FormAlarm(FormMain mainForm)
        {
            InitializeComponent();
            this.EnableGlass = false;
            this._mainForm = mainForm;  
        }

        private void bI_Export_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                List<SingleWarnInfo> alarmList = new List<SingleWarnInfo>();
                foreach (var item in sGC_PLC.PrimaryGrid.Rows)
                {
                    alarmList.Add(item.Tag as SingleWarnInfo);
                }
                CsvOperator<SingleWarnInfo> csvOperator = new CsvOperator<SingleWarnInfo>();
                string errInfo = "";
                csvOperator.WriteCSV(saveFileDialog.FileName, alarmList, out errInfo);
                if(!string.IsNullOrEmpty(errInfo))
                {
                    MessageBox.Show(errInfo);
                }
            }
        }

        private void bI_Clear_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定清除所有报警记录吗?", "报警清除", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                this.sGC_PLC.PrimaryGrid.Rows.Clear();
            }
        }
        public void addOneAlarm(MachineMessage message)
        {
            GridRow gridRow = new GridRow();
            gridRow.Tag = message;  

            GridCell cell = new GridCell();
            cell.Value = message.StartTime.ToString("yyyy-MM-dd HH:mm:ss");
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);
            cell = new GridCell();
            cell.Value = EnumHelper.GetEnumDescriptionFromValue(message.MessageType);
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);
            cell = new GridCell();
            cell.Value = message.MessageSource;
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);
            cell = new GridCell();
            cell.Value = message.MessageBody;
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);
            cell = new GridCell();
            cell.Value = message.Module;
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);

            if (message.MessageType == MessageType.Warn)
                gridRow.CellStyles.Default.TextColor = Color.Orange;
            else if (message.MessageType == MessageType.Error)
                gridRow.CellStyles.Default.TextColor = Color.IndianRed;
            else if (message.MessageType == MessageType.InfoAndPause)
                gridRow.CellStyles.Default.TextColor = Color.Yellow;

            this.sGC_PLC.PrimaryGrid.Rows.Add(gridRow);
        }
        public void addOneAlarm(DateTime startTime, string messageType, string messageSource, string messageBody, string messageModule)
        {
            GridRow gridRow = new GridRow();
            SingleWarnInfo swi = new SingleWarnInfo(startTime, messageType, messageSource, messageBody, messageModule);
            gridRow.Tag = swi;

            GridCell cell = new GridCell();
            cell.Value = startTime.ToString("yyyy-MM-dd HH:mm:ss");
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);
            cell = new GridCell();
            cell.Value = messageType;
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);
            cell = new GridCell();
            cell.Value = messageSource;
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);
            cell = new GridCell();
            cell.Value = messageBody;
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);
            cell = new GridCell();
            cell.Value = messageModule;
            cell.ReadOnly = true;
            gridRow.Cells.Add(cell);

            if (messageType.Equals("警报"))
                gridRow.CellStyles.Default.TextColor = Color.Orange;
            else if (messageType.Equals("错误"))
                gridRow.CellStyles.Default.TextColor = Color.IndianRed;

            this.sGC_PLC.PrimaryGrid.Rows.Add(gridRow);
        }

        private void FormAlarm_Load(object sender, EventArgs e)
        {
            string errInfo = "";
            DataTable dt = _mainForm.Select($"select * from WarnList where StartTime > '{DateTime.Now.ToString("yyyy-MM-dd")}';", out errInfo);
            if(dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    addOneAlarm((DateTime)dr["StartTime"], dr["Level"].ToString(), dr["Source"].ToString(), dr["Content"].ToString(), dr["Module"].ToString());
                }
            }
            cB_Level.Items.AddRange(new object[] { "警报", "错误", "提示" });
            cB_Level.SelectedIndex = -1;
            cB_Module.Items.AddRange(MachineResource.Instance.GetAllModuleNames().ToArray());
            cB_Module.SelectedIndex = -1;
            cB_Source.Items.AddRange(FlowManager.Instance.Flows.Keys.ToArray());
            cB_Source.SelectedIndex = -1;
            tB_Content.Text = "";
            dTP_Start.Value = DateTime.Now;
            dTP_End.Value = DateTime.Now.AddDays(1);
        }

        private void btn_Search_Click(object sender, EventArgs e)
        {
            if(!checkRule())
            {
                MessageBox.Show("搜索条件有误!", "查找", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            sGC_PLC.PrimaryGrid.Rows.Clear();

            string timeExp = "";
            if (startTime.Year < 2022 || endTime.Year < 2022)
                timeExp = "";
            else
                timeExp = $" StartTime > '{startTime.ToString("yyyy-MM-dd")}' and StartTime < '{endTime.ToString("yyyy-MM-dd")}'";
            string levelExp = cB_Level.SelectedIndex == -1 ? "" : $"Level = '{cB_Level.Text}'";
            string sourceExp = cB_Source.SelectedIndex == -1 ? "" : $"Source = '{cB_Source.Text}'";
            string moduleExp = cB_Module.SelectedIndex == -1 ? "" : $"Module = '{cB_Module.Text}'";
            string contentExp = tB_Content.Text == "" ? "" : $"Content like '%{tB_Content.Text}%'";
            //string contentExp = tB_Content.Text == "" ? "" : $"Content = '{tB_Content.Text}'";
            string errInfo = "";
            string expression = "";
            expression = "select * from WarnList where ";
            List<string> paramList = new List<string>();
            if (!string.IsNullOrEmpty(timeExp))
                paramList.Add(timeExp);
            if (!string.IsNullOrEmpty(levelExp))
                paramList.Add(levelExp);
            if (!string.IsNullOrEmpty(sourceExp))
                paramList.Add(sourceExp);
            if (!string.IsNullOrEmpty(moduleExp))
                paramList.Add(moduleExp);
            if (!string.IsNullOrEmpty(contentExp))
                paramList.Add(contentExp);
            if (string.IsNullOrEmpty(timeExp) && string.IsNullOrEmpty(sourceExp) && string.IsNullOrEmpty(moduleExp) && string.IsNullOrEmpty(contentExp))
                expression = "select * from WarnList;";
            else
            {
                for (int i = 0; i < paramList.Count; i++)
                {
                    if (i == paramList.Count - 1 && i != 0)
                    {
                        expression += " and ";
                        expression += paramList[i];
                        expression += ';';
                    }
                    else if(i == 0)
                    {
                        expression += paramList[i];
                    }
                    else
                    {
                        expression += " and ";
                        expression += paramList[i];
                    }
                }
            }
            DataTable dt = _mainForm.Select(expression, out errInfo);
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    addOneAlarm((DateTime)dr["StartTime"], dr["Level"].ToString(), dr["Source"].ToString(), dr["Content"].ToString(), dr["Module"].ToString());
                }
            }
            if(!string.IsNullOrEmpty(errInfo))
            {
                MessageBox.Show($"查询失败:{errInfo}", "查询", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private bool checkRule()
        {
            if (endTime < startTime)
                return false;
            return true;
        }
        private void btn_Clear_Click(object sender, EventArgs e)
        {
            dTP_Start.Value = DateTime.Now;
            dTP_End.Value = DateTime.Now.AddDays(1);
            cB_Level.SelectedIndex = -1;
            cB_Module.SelectedIndex = -1;
            cB_Source.SelectedIndex = -1;
            tB_Content.Text = "";
        }
        DateTime startTime;
        DateTime endTime;
        private void dTP_Start_ValueChanged(object sender, EventArgs e)
        {
            startTime = dTP_Start.Value;
        }

        private void dTP_End_ValueChanged(object sender, EventArgs e)
        {
            endTime = dTP_End.Value;
        }
    }
    public class SingleWarnInfo : ICsv
    {
        public DateTime StartTime { get; set; }
        public string Level { get; set; }
        public string Content { get; set; }
        public string Module { get; set; }
        public string Source { get; set; }
        public SerializableDictionary<string, string> CsvName2Property { get; set; }
        public SingleWarnInfo()
        {

        }
        public SingleWarnInfo(DateTime startTime, string level, string source, string content, string module)
            :this()
        {
            this.StartTime = startTime;
            this.Content = content;
            this.Source = source;
            this.Level = level;
            this.Module = module;

            this.CsvName2Property = new SerializableDictionary<string, string>(); 
            this.CsvName2Property.Add("发生时间", nameof(StartTime));
            this.CsvName2Property.Add("报警等级", nameof(Level));
            this.CsvName2Property.Add("报警来源", nameof(Source));
            this.CsvName2Property.Add("报警内容", nameof(Content));
            this.CsvName2Property.Add("所属模组", nameof(Module));
        }
    }
}
